package se.perp.c4.control.bot;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import se.perp.c4.control.iface.IConnectionListener;
import se.perp.c4.net.IConnection;
import se.perp.c4.net.Message;

class BotConnection implements IConnection, IBotSideConnection {

    final private Queue<Message> toBotQueue = new ConcurrentLinkedQueue<Message>();
    final private Queue<Message> fromBotQueue = new ConcurrentLinkedQueue<Message>();

    public BotConnection() {
    }

    public boolean isServer() {
        return true;
    }

    public void sendMessage(Message m) {
        System.out.println("[BotConnection] Sending message of type " + m.getType() + " to bot.");
        toBotQueue.add(m);
        System.out.println("[BotConnection] Queue TO bot: " + toBotQueue);
    }

    public Message waitForNextMessage() {
        System.out.println("[BotConnection] Waiting for next message from bot.");
        Message m;
        while (fromBotQueue.peek() == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                Logger.getLogger(BotConnection.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        m = fromBotQueue.poll();

        System.out.println("[BotConnection] Got message from fromBotQueue: " + m);
        return m;
    }

    public void close() {
        // Empty
    }

    public void setConnectionListener(IConnectionListener l) {
        // Empty
    }

    public void sendToPlayer(Message m) {
        fromBotQueue.add(m);
    }

    public Message waitForPlayerMessage() {
        Message m;
        System.out.println("[BotConnection] waitForPlayerMessage()");
        while (toBotQueue.peek() == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
        }
        m = toBotQueue.poll();
        System.out.println("[BotConnection] Got message from toBotQueue: " + m);
        return m;

    }
}
